package commons;

import javax.servlet.http.HttpServletRequest;

import commons.data.Page;


public class PageHandler {
	//默认页面数据数=10条
	private static final int COUNT = 10;

	public static Page process(HttpServletRequest request, long total) {
		Page p = new Page();
		
		p.setTotal(total);

		//当前页数
		try {
			String page = request.getParameter("page");
			p.setPage(Integer.valueOf(page));
		} catch (Exception e) {
			p.setPage(1);
		}
		
		//当前页书数据行数
		try {
			String count = request.getParameter("count");
			p.setCount(Integer.valueOf(count));
		} catch (Exception e) {
			p.setCount(COUNT);
		}
		
		//数据起始值
		p.setBegin((p.getPage() - 1) * p.getCount());
		
		//总页数
		int pageSum = (int) (total / p.getCount());
		if(pageSum == 0) {
			pageSum = 1;
		}else if(total % p.getCount() > 0) {
			pageSum++;
		}
		p.setPageSum(pageSum);
		
		//分页起始页数&终止页数
		if(pageSum > 6) {
			if(p.getPage() > 4) {
				if(p.getPage() + 2 > pageSum) {
					p.setOver(pageSum);
					p.setStart(pageSum - 5);
				}else {
					p.setOver(p.getPage() + 2);
					p.setStart(p.getOver() - 5);
				}
			}else {
				p.setStart(1);
				p.setOver(6);
			}
		}else {
			p.setStart(1);
			p.setOver(pageSum);
		}
		
		//next
		int next = p.getPage() + 1;
		if(next > pageSum) {
			next = pageSum;
		}
		p.setNext(next);
		
		//last
		int last = p.getPage() - 1;
		if(last < 1) {
			last = 1;
		}
		p.setLast(last);
		
		//将分页信息放入request中，可以在JSP中调用
		request.setAttribute("page", p);
		
		return p;
	}
}